package com.deyou.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.MyTravelAdapter;
import com.deyou.adapter.OrderItemAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.CollectionBean;
import com.deyou.model.HomePageCityBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.OrderBean;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscription;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class OrderListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_tab_one)
    TextView tvTabOne;
    @BindView(R.id.tab_line_one)
    View tabLineOne;
    @BindView(R.id.tab_one_layout)
    RelativeLayout tabOneLayout;
    @BindView(R.id.tv_tab_two)
    TextView tvTabTwo;
    @BindView(R.id.tab_line_two)
    View tabLineTwo;
    @BindView(R.id.tab_two_layout)
    RelativeLayout tabTwoLayout;
    @BindView(R.id.tv_tab_three)
    TextView tvTabThree;
    @BindView(R.id.tab_line_three)
    View tabLineThree;
    @BindView(R.id.tab_three_layout)
    RelativeLayout tabThreeLayout;
    @BindView(R.id.tv_tab_four)
    TextView tvTabFour;
    @BindView(R.id.tab_line_four)
    View tabLineFour;
    @BindView(R.id.tab_four_layout)
    RelativeLayout tabFourLayout;
    @BindView(R.id.tv_tab_five)
    TextView tvTabFive;
    @BindView(R.id.tab_line_five)
    View tabLineFive;
    @BindView(R.id.tab_five_layout)
    RelativeLayout tabFiveLayout;
    @BindView(R.id.order_recycler_view)
    RecyclerView orderRecyclerView;
    @BindView(R.id.order_refresh_layout)
    SwipeRefreshLayout orderRefreshLayout;

    private int orderStatus = 0; // 0-待确认  1-待付款 2-待入住 3-待评价 4-全部
    private OrderItemAdapter mAdapter;
    private List<HomePageCityBean> travelList = new ArrayList<>();
    private int page = 1;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);
        ButterKnife.bind(this);
        initView();
        initListener();
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    private void initView() {
        tvMidTitle.setText("订单管理");
        orderStatus = 0;

        orderRecyclerView.setItemAnimator(new DefaultItemAnimator());
        orderRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        orderRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
        mAdapter = new OrderItemAdapter(OrderListActivity.this);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnLoadMoreListener(this, orderRecyclerView);
        orderRecyclerView.setAdapter(mAdapter);
        orderRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        orderRefreshLayout.setOnRefreshListener(this);
        setRefreshing(true);
        onRefresh();
    }

    private void initListener() {
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.btn_cancel_travel:
                        break;
                    case R.id.btn_pay_travel:
                        Bundle bundle = new Bundle();
                        bundle.putString("orderId", mAdapter.getData().get(position).orderId);
                        AndroidUtils.startNextActivity(OrderListActivity.this, PayOrderActivity.class, bundle, false);
                        break;
                    case R.id.btn_comment_travel:
                        showToast("确认订单");
                        break;
                }
            }
        });
    }

    private void getOrderList() {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", SPUtils.getStringByKey(this, Constants.UserId));
            object.put("page", page);
            object.put("size", Constants.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();

        Type type = new TypeToken<LzyResponse<OrderBean>>() {
        }.getType();
        ServerApi.<LzyResponse<OrderBean>>getData(type, Urls.getOrderList, "", AESUtil.encrypt(paramJson))//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        if (!isRefresh && !isLoadMore)
                            showLoading();
                    }
                })//
                .map(new Function<LzyResponse<OrderBean>, OrderBean>() {
                    @Override
                    public OrderBean apply(@NonNull LzyResponse<OrderBean> response) throws Exception {
                        return response.data;
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<OrderBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull OrderBean bean) {
                        if (null != bean) {
                            setRefreshing(false);
                            dismissLoading();
                            mAdapter.loadMoreComplete();
                            if (bean.pageNum == 1)
                                mAdapter.setNewData(bean.list);
                            else
                                mAdapter.addData(bean.list);
                            if (bean.pages > 1 && page < bean.pages)
                                mAdapter.setEnableLoadMore(true);
                            else
                                mAdapter.setEnableLoadMore(false);
                        } else {
                            mAdapter.loadMoreComplete();
                            dismissLoading();
                            setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        Toast.makeText(OrderListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                        mAdapter.loadMoreComplete();
                        dismissLoading();
                        setRefreshing(false);
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: // 没有数据
                    if (page == 1) {
                    } else {
                    }
                    break;
                case 2:
                    break;
            }
        }
    };

    @OnClick({R.id.iv_left_back, R.id.tab_one_layout, R.id.tab_two_layout, R.id.tab_three_layout, R.id.tab_four_layout, R.id.tab_five_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.tab_one_layout:
                dealOrderStatusTitle(1);
                break;
            case R.id.tab_two_layout:
                dealOrderStatusTitle(2);
                break;
            case R.id.tab_three_layout:
                dealOrderStatusTitle(3);
                break;
            case R.id.tab_four_layout:
                dealOrderStatusTitle(4);
                break;
            case R.id.tab_five_layout:
                dealOrderStatusTitle(5);
                break;
        }
    }

    private void dealOrderStatusTitle(int status) {
        setRefreshing(true);
        onRefresh();
        tabLineOne.setVisibility(View.GONE);
        tvTabOne.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineTwo.setVisibility(View.GONE);
        tvTabTwo.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineThree.setVisibility(View.GONE);
        tvTabThree.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineFour.setVisibility(View.GONE);
        tvTabFour.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineFive.setVisibility(View.GONE);
        tvTabFive.setTextColor(getResources().getColor(R.color.color_272424));
        switch (status) {
            case 1:
                tabLineOne.setVisibility(View.VISIBLE);
                tvTabOne.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 2:
                tabLineTwo.setVisibility(View.VISIBLE);
                tvTabTwo.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 3:
                tabLineThree.setVisibility(View.VISIBLE);
                tvTabThree.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 4:
                tabLineFour.setVisibility(View.VISIBLE);
                tvTabFour.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 5:
                tabLineFive.setVisibility(View.VISIBLE);
                tvTabFive.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
        }
    }

    public void setRefreshing(final boolean refreshing) {
        orderRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                orderRefreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        setRefreshing(false);
        page = 1;
        getOrderList();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        AndroidUtils.startNextActivity(this, OrderDetailActivity.class, null, false);
    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        getOrderList();
    }
}
